// 引入接口文件
import { getList,getDetail,seckillOrderRedeem,down} from './orderListServ'

// 对象和JSON字符串互转
import { parse } from 'qs'
// 弹出消息框
import { message } from 'antd'
// 日期处理对象
import moment from 'moment'
/* isEmpty 对象是否为空
 * isArray 对象是否数组
 * cloneDeep 对象深拷贝
 */
import {isEmpty, isArray, cloneDeep, merge} from 'lodash'
// 引入路由对象
import { hashHistory } from 'dva/router'
import config from 'config/config';
import { download } from 'utils/util'


const queryList = [
  {name: '项目名称或商品名称', type: 'text', key: 'projectName', value: ''},
  {name: '活动名称', type: 'text', key: 'activityName', value: ''},
  {name: '客户姓名', type: 'text', key: 'accountName', value: ''},
  {
    name: '商品类型', type: 'select', key: 'productType', value: '', notNeedAll: true, list: [
      {id: '', name: '全部'},
      {id: '1', name: '房源'},
      {id: '2', name: '停车位'},
      {id: '3', name: '商铺'},
      {id: '4', name: '日用快消'},
      {id: '5', name: '家电数码'},
      {id: '6', name: '首饰箱包'},
      {id: '7', name: '其他'},
    ]
  },
  {
    name: '订单类型', type: 'select', key: 'orderType', value: '', notNeedAll: true, list: [
      {id: '', name: '全部'},
      {id: '1', name: '报名费'},
      {id: '2', name: '订金'},
    ]
  },
  {
    name: '订单状态', type: 'select', key: 'status', value: '', notNeedAll: true, list: [
      {id: '', name: '全部'},
      {id: '1', name: '待支付'},
      {id: '2', name: '已支付'},
      {id: '3', name: '支付超时'},
      {id: '8', name: '待退款'},
      {id: '9', name: '已退款'},
    ]
  },
]

// 初始默认状态
const defultState = {
  loading: false,
  exportLoading: false,
  btnLoading: false,
  queryList,
  currentItem: {},
  modalObj:{
    visible:false,
  },
  productSelf: [],
  activeKey: '1',
  // 表格数据
  tableData: {
    dataSource: [

    ],
    total: 0,
    stop:0,
    start:0
  },
  // 表格分页设置
  pageConfig: {
    pageSize: Number.parseInt(config.smallPageSizeList[0]),
    pageNo: 1
  },
  rewardModal:false,
  rewardObj:{}
}

// 声明module
const tmpModule = {
  // namespace: 'productListModel',
  // 默认状态
  state: cloneDeep(defultState),
  // 入口函数(先执行)
  subscriptions: {
    setup ({dispatch, history}) {
      history.listen(({ pathname, query }) => {
        // 页面路由匹配时执行
        if('' + tmpModule.pathname === '' + pathname){
          // dispatch({ type: 'updateStore', payload: {...cloneDeep(defultState), ...query} });//每次进去页面先重置状态
          // 执行业务操作
          dispatch({
            type: 'search',
            payload: {}
          }) // end dispatch
        } // end if
      }) // end listen
    },
  },

  // 方法列表
  effects: {
    * down ({payload}, {put, call, select}) {
      try {
        let {queryList} = yield select(state => state[tmpModule.namespace])
        //组装接口入参
        let params = {
          sellType: '1',
        };
        queryList.map(item => {
          params[item.key] = item.value;
        });
        const {data, success} = yield call(down,params)
        yield put({type: 'updateStore', payload: {exportLoading: false}})
        if (success) {
          // yield put({ type: 'updateStore', payload: {  data } });
          let url = data || ''
          if (url) {
            download(url)
          }
          message.success('操作成功')
          // window.open(data.url)
          
        }
      } catch (e) {
        console.error(e)
      }
    },
    //查询操作
    *search({ payload = {} }, { call, put, select }) {
      let {queryList,tableData,pageConfig} = yield select(state => state[tmpModule.namespace])
      const  pageSize = pageConfig.pageSize;
      

      //组装接口入参
      let params = {
        sellType: '1',
      };
      queryList.map(item => {
        // if(item.key=='status'){
        //   item.value=Number(item.value)
        // }
        params[item.key] = item.value;
      });
      //显示loading状态
      yield put({type: 'updateStore', payload: {loading: true, btnLoading: true,}})
      const {rows,success,msg,total,pageNo} = yield call(getList, { ...params, pageNo: payload.pageNo||1, pageSize, });
      yield put({ type: 'updateStore', payload: { loading: false,btnLoading: false, } })
      console.log('数据',rows,success,msg,total,pageNo);
      if (success) {
        let list=rows
        list.map((item,index)=>{
          item.key = index+1;
        });
        tableData = {
          dataSource: list,
          total:Number(total)
        }
        yield put({
          type: 'updateStore', payload: {
            pageConfig: {...pageConfig, pageNo},
            tableData,
          }
        })
      }
    },
    *pageChange({ payload }, { put, select }) {
      const { pageNo, pageSize } = payload;
      const { pageConfig } =yield select(state => state[tmpModule.namespace])
      yield put({ type: 'updateStore', payload: { pageConfig: { ...pageConfig, ...payload } } });
      yield put({ type: 'search', payload: { pageNo, pageSize } });
    },
    //改变查询条件
    *inputChange({ payload }, { call, put, select }) {
      let { queryList } = yield select(state => state[tmpModule.namespace])
      const { key, value } = payload;
      let data = queryList.find(item => item.key === key);
      data.value = value;
      yield put({ type: 'updateStore', payload: { queryList: [...queryList, ...data] } });
    },
    // 查询条件重置
    *queryReset({ }, { put }) {
      yield put({ type: 'updateStore', payload: { queryList: cloneDeep(queryList) } });
      // yield put({ type: 'search' })
    },
    // 详情
    *getDetail({payload }, { put,select,call}) {
      try{
        let { queryList ,tableData} = yield select(state => state[tmpModule.namespace])
        let {id,index}=payload
        let currentItem=tableData.dataSource[index]||{}
        if(tableData.dataSource[index]['currentItem']){
          currentItem=tableData.dataSource[index]['currentItem']
        }else{
          const {success,msg,data={}} = yield call(getDetail, {sellType: '1',id:payload.id });
        
        console.log('数据',success,msg,data,payload);
          if(success){
            currentItem=Object.assign(currentItem,data)
            tableData.dataSource[index]['currentItem']=currentItem
            currentItem['cardNo']=currentItem['cardNo']?currentItem['cardNo'].replace(/^(.{4})(?:\d+)(.{4})$/,"$1**********$2"):""
          }
        }
        yield put({ type: 'updateStore', payload: { tableData,currentItem}});
      }catch(e){
        console.log(e)
      }
     
    },
    *seckillOrderRedeem ({payload}, {put, select, call}) {
      let { pageConfig } = yield select(state => state[tmpModule.namespace])
      const { pageNo, pageSize } = pageConfig;
      const {success, msg, data} = yield call(seckillOrderRedeem,payload.rewardObj)
      if(success){
        message.success(msg);
        yield put({ type: 'search', payload: { pageNo,pageSize}});
      }
    },

  },

  // 存入状态机
  reducers: {
    updateStore(preState, action) {
      return Object.assign({}, preState, action.payload)
    },
  }
}

export default tmpModule
